package io.dogstudio.apt;

import android.app.Activity;
import android.text.TextUtils;
import android.view.View;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * TODO 类描述
 *
 * @author HB.cby
 * @date 2020-10-28
 **/
public class ViewBinding {
	interface ViewBindListener {
		View findViewById(int resID);
	}

	@Retention(RetentionPolicy.RUNTIME)
	@Target(ElementType.FIELD)
	@interface AutoWire {
		int value();
	}

	static class Config {
		public Field field;
		public int viewID;

		public Config(Field field, int viewID) {
			this.field = field;
			this.viewID = viewID;
		}
	}

	public void bind(Activity activity) {
		Class clazz = activity.getClass();
		Field[] fields = clazz.getDeclaredFields();
		ViewBindListener proxy = createProxy(activity);
		for (Field field : fields) {
			AutoWire autoWire = field.getAnnotation(AutoWire.class);
			if (autoWire != null) {
				field.setAccessible(true);
				try {
					field.set(activity, proxy.findViewById(autoWire.value()));
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
			}
		}
	}


	public ViewBindListener createProxy(Activity activity) {
		return (ViewBindListener) Proxy.newProxyInstance(activity.getClass().getClassLoader(),
				new Class[]{ViewBindListener.class}, (o, method, objects) -> {
					if (TextUtils.equals(method.getName(), "findViewById")) {
						return activity.findViewById((Integer) objects[0]);
					} else {
						return null;
					}
				});
	}

}
